<template>
  <div class="home-container">
    <el-row :gutter="24" class="main-row">
      <el-col :xs="24" :sm="24" :md="16" :lg="17">
        <div class="article-list">
          <el-card v-for="article in articles" :key="article.id" class="article-card">
            <div class="article-header">
              <span class="article-title">{{ article.title }}</span>
              <div class="article-tags">
                <el-tag v-for="tag in article.tags" :key="tag" type="info" size="small">{{ tag }}</el-tag>
              </div>
            </div>
            <div class="article-meta">
              <span>{{ article.created_time }}</span>
              <span style="margin-left: 16px;">{{ article.views }} 阅读</span>
            </div>
            <v-md-editor :model-value="article.body" mode="preview" />
            <el-button type="primary" size="small" class="read-more" @click="toArticleDetail(article.id)">阅读全文</el-button>
          </el-card>
          
          <!-- 修改为简单的上一页/下一页分页 -->
          <div class="pagination-container">
            <el-pagination
              v-model:current-page="currentPage"
              :page-size="pageSize"
              :page-count="999999"
              layout="prev, next"
              :prev-text="'上一页'"
              :next-text="'下一页'"
              :disabled-prev="currentPage <= 1"
              :disabled-next="!hasNextPage"
              @prev-click="handlePrevClick"
              @next-click="handleNextClick"
            />
          </div>
        </div>
      </el-col>
      <el-col :xs="24" :sm="24" :md="8" :lg="7">
        <Sidebar />
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import Sidebar from '@/components/Sidebar.vue';
import blogApi from '../api/blog.js';
import router from '../router/index.js';
import { ref , onMounted, watch} from 'vue';
import { useUserStore } from "../stores/user.js";
import { useRoute } from 'vue-router'
import { useTabStore } from '../stores/tab.js'

const tabStore = useTabStore();
const route = useRoute();

const userStore = useUserStore();
const articles = ref([]);
const category = ref('');

// 分页相关响应式数据
const currentPage = ref(1);
const pageSize = ref(10);
const hasNextPage = ref(false);
const showPagination = ref(false);

// 正常数据， 默认按照index排序的发布文章
const GetArticleWithTagsList = async (limit, offset, category) => {
  const res = await blogApi.GetArticleWithTagsList(limit, offset, category);
  if (res.code === 0) {
    articles.value = res.data || [];
    // 判断是否有下一页（如果返回的数据数量等于或大于请求的数量，则认为有下一页）
    hasNextPage.value = articles.value.length >= limit;
    showPagination.value = articles.value.length > 0;
    console.log("分页展示：",showPagination.value);
    console.log("分页当前页:", currentPage.value);
    
  }
}


// 查看自己的隐私个人文章
const GetMyArticleWithTagsList = async (limit, offset) => {
  const res = await blogApi.GetMyArticleWithTagsList(limit, offset, userStore.state.user_id);
  if (res.code === 0) {
    articles.value = res.data || [];
    hasNextPage.value = articles.value.length >= limit;
    showPagination.value = articles.value.length > 0;
  }
}

// 搜索文章
const SearchArticleWithTagsListByKeyword = async (limit, offset, keyword) => {
  const data = {
    limit,
    offset,
    keyword,
    user_id: 0,
  }
  const res = await blogApi.EsSearchArticles(data);
  if (res.code === 0) {
    articles.value = res.data || [];
    hasNextPage.value = articles.value.length >= limit;
    showPagination.value = articles.value.length > 0;
  }
}

// 搜索自己的文章
const SearchMyArticleWithTagsListByKeyword = async (limit, offset, keyword) => {
  const data = {
    limit,
    offset,
    keyword,
    user_id: userStore.state.user_id,
  }
  const res = await blogApi.EsSearchArticles(data);
  if (res.code === 0) {
    articles.value = res.data || [];
    hasNextPage.value = articles.value.length >= limit;
    showPagination.value = articles.value.length > 0;
  }
}

const toArticleDetail = (id) => {
  router.push({
    path: `/article/${id}`,
  });
}

// 获取的是默认文章列表， 或者自己的隐私文章
const fetchArticles = async (tab) => {
  const offset = (currentPage.value - 1) * pageSize.value;
  
  if (tab === 'my') {
    GetMyArticleWithTagsList(pageSize.value, offset);
  } else {
    GetArticleWithTagsList(pageSize.value, offset, category.value);
  }
}

// 上一页处理函数
const handlePrevClick = () => {
  if (currentPage.value > 1) {
    fetchCurrentArticles();
  }
}

// 下一页处理函数
const handleNextClick = () => {
  if (hasNextPage.value) {
    fetchCurrentArticles();
  }
}

// 获取当前条件下的文章列表
const fetchCurrentArticles = () => {
  const keyword = tabStore.searchKeyword;
  const tab = tabStore.currentTab;
  const offset = (currentPage.value - 1) * pageSize.value;
  
  if (keyword) {
    if (tab === 'my') {
      SearchMyArticleWithTagsListByKeyword(pageSize.value, offset, keyword);
    } else {
      SearchArticleWithTagsListByKeyword(pageSize.value, offset, keyword);
    }
  } else {
    fetchArticles(tab);
  }
}

// 监控他点击了哪个导航栏哪个tab
watch(() => tabStore.currentTab, (newTab) => {
  currentPage.value = 1; // 切换标签时重置为第一页
  fetchArticles(newTab);
})

// 监控搜索关键词变化
// 监控分类变化
watch(() => tabStore.category, (newCategory) => {
  currentPage.value = 1; // 切换分类时重置为第一页
  category.value = newCategory;
  fetchArticles(tabStore.currentTab);
})



watch(() => tabStore.searchKeyword, (newKeyword) => {
  currentPage.value = 1; // 搜索时重置为第一页
  
  if (newKeyword) {
    const offset = (currentPage.value - 1) * pageSize.value;
    if (tabStore.currentTab === 'my') {
      SearchMyArticleWithTagsListByKeyword(pageSize.value, offset, newKeyword);
    } else {
      SearchArticleWithTagsListByKeyword(pageSize.value, offset, newKeyword);
    }
  } else {
    fetchArticles(tabStore.currentTab);
  }
})

// // 监听 tab 参数变化
// watch(() => route.query.tab, (newTab) => {
//   fetchArticles(newTab)
// })



// GetArticleWithTagsList(10, 0);
onMounted(() => {
  fetchArticles(route.query.tab);
  tabStore.setPageName(route.name)
})

</script>

<style scoped>
.home-container {
  background: var(--main-bg);
  min-height: 100vh;
  padding-top: 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100%;
}

.main-row {
  width: 100%;
  max-width: 1200px;
  margin: 0 auto;
  padding-top: 24px; /* 添加顶部间距 */
}


.article-card {
  margin-bottom: 24px;
  box-shadow: 0 2px 8px var(--shadow) !important;
  border-radius: 8px;
  border: 1px solid var(--border-color) !important;
  transition: all 0.3s ease;
}

.article-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 12px;
}

.article-title {
  font-size: 20px;
  font-weight: bold;
  color: var(--text-primary);
  transition: color 0.3s ease;
}

.dark-theme .article-title {
  color: #e1e1e6;  /* 暗色模式下标题用浅灰白色 */
}

.article-tags {
  display: flex;
  gap: 8px;
}

.article-meta {
  color: var(--text-secondary);
  font-size: 13px;
  margin: 12px 0;
}

.dark-theme .article-meta {
  color: #8b8b8d;  /* 暗色模式下元信息用中灰色 */
}

.article-summary {
  color: var(--text-primary);
  font-size: 15px;
  line-height: 1.7;
  margin: 16px 0;
}

.dark-theme .article-summary {
  color: #b4b4b8;  /* 暗色模式下正文内容用亮灰色 */
}

.read-more {
  float: right;
  margin-top: 16px;
  background-color: var(--highlight) !important;
  border-color: var(--highlight) !important;
}

.dark-theme .read-more {
  background-color: #4f9eff !important; /* 暗色模式下按钮用亮蓝色 */
  border-color: #4f9eff !important;
  color: #ffffff !important;
}

.dark-theme .read-more:hover {
  opacity: 0.9;
}

/* 标签样式优化 */
.dark-theme .el-tag {
  background-color: #2a2a2a !important;
  border-color: #3a3a3a !important;
  color: #a0a0a0 !important;
}

</style>